package com.njtoyo.taxi.admin.library.payment.cmb.file.http;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.njtoyo.taxi.admin.library.payment.cmb.file.SignUtil;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class);

    private static final String APPID = "appid";
    private static final String TIMESTAMP = "timestamp";
    private static final String SIGN = "sign";
    private static final String APISIGN = "apisign";
    private static final String VERIFY = "verify";
    private static final String VERSION = "version";
    private static final MediaType JSONHeader = MediaType.parse("application/json; charset=utf-8");

    private static OkHttpClient client;

    static {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            X509TrustManager x509TrustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{};
                }
            };

            TrustManager[] trustAllCerts = new TrustManager[]{x509TrustManager};
            sslContext.init(null, trustAllCerts, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            client = new OkHttpClient.Builder()
                    .readTimeout(60, TimeUnit.SECONDS)
                    //                    忽略证书验证，根据安全性需要选择
                    .sslSocketFactory(sslSocketFactory, x509TrustManager)
                    .hostnameVerifier((s, sslSession) -> true)
                    .build();
        } catch (Exception e) {
            System.out.println("OkHttpClient初始化失败，" + e.getMessage());
        }
    }

    public static Map<String, String> createHeaders(RequestConfig requestConfig, String params) throws Exception {
        Map<String, String> map = new HashMap<>();

        String timestamp = String.valueOf(new Date().getTime() / 1000);

        String sign =  SignUtil.sm3Signature2(params);

        List<String> list = new ArrayList<>();
        list.add("appid=" + requestConfig.getAppId());
        list.add("secret=" + requestConfig.getAppSecret());
        list.add("sign=" + sign);
        list.add("timestamp=" + timestamp);
        String src = String.join("&", list);

        String apisign = SignUtil.sm3withSm2Signature(requestConfig.getPrivateKey(), src);

        map.put("appid", requestConfig.getAppId());
        map.put("timestamp", timestamp);
        map.put("sign", sign);
        map.put("apisign", apisign);
        map.put("verify", requestConfig.getVerify());
        map.put("version", requestConfig.getVersion());

        return map;
    }

    public static String formatGetUrl(String url, Map<String, Object> bizParams) {
        if (null == bizParams) {
            return url;
        }
        StringBuilder sb = new StringBuilder(url).append("?");
        for (String s : bizParams.keySet()) {
            sb.append(s).append("=").append(bizParams.get(s)).append("&");
        }
        return sb.substring(0, sb.length() - 1);
    }

    public static <T> T request(String url, HttpMethod httpMethod,
                                Map<String, String> headers, String bodyBizParams, String bankPubKey) {
        Assert.notBlank(url);
        Assert.notNull(headers);
        Assert.notNull(httpMethod);

        RequestBody body = null != bodyBizParams ? RequestBody.create(JSONHeader, bodyBizParams) : null;
        Request.Builder builder = new Request.Builder().url(url).method(httpMethod.name(), body);
        headers.forEach(builder::addHeader);
        Request request = builder.build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求异常，返回code：" + response.code() + "，返回message：" + response.message());
            }

            String bodySign = response.header("CMB-BodySign");
            ResponseBody resBody = response.body();
            if (null == resBody) {
                LOGGER.error("响应body为空，响应内容为：{}", response);
                return null;
            }

            String bodyStr = resBody.string();
            if (null != bodySign) {
                boolean verify = SignUtil.verify(bankPubKey, bodyStr, bodySign);
                if (!verify) {
                    LOGGER.error("响应body验签失败，响应签名为：{}", bodySign);
                    // 验签失败业务逻辑
                }
            }

            return JSON.parseObject(bodyStr, new TypeReference<T>() {});

        } catch (Exception e) {
            LOGGER.error("请求发生异常，", e);
            return null;
        } finally {
            if (null != response && null != response.body()) {
                response.body().close();
            }
        }
    }

    /**
     * 文件上传
     *
     * @param contentType {@link ContentType}
     */
    public static boolean uploadFile(String url, File file, String contentType) {
        Assert.notBlank(url);
        Assert.notNull(file);
        Assert.notBlank(contentType);

        RequestBody requestBody = MultipartBody.create(MediaType.parse(contentType), file);

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", contentType)
                .put(requestBody)
                .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.code() == 403) {
                System.out.println("链接已过期或文件格式错误");
            }
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 返回2xx表示上传成功
            return true;

        } catch (IOException e) {
            System.out.println("文件上传发生异常，" + e.getMessage());
            return false;
        } finally {
            if (null != response && null != response.body()) {
                response.body().close();
            }
        }
    }


}
